﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;

namespace System.Controls
{
  public class ItemsControl : System.Windows.Controls.ItemsControl
  {
    public static readonly DependencyProperty GroupNameProperty =
      DependencyProperty.Register( "GroupName",
        typeof( string ), typeof( ItemsControl ),
        new PropertyMetadata( "RadioGroup" ) );

    public static readonly DependencyProperty ContainerTypeProperty =
      DependencyProperty.Register( "ContainerType",
        typeof( Type ), typeof( ItemsControl ) );

    public ItemsControl()
    {
      ItemContainerGenerator.StatusChanged += ( sender, arg )=>GeneratorStateChanged( ItemContainerGenerator.Status );
    }

    public string GroupName
    {
      get { return (string)GetValue( GroupNameProperty ); }
      set { SetValue( GroupNameProperty, value ); }
    }

    public Type ContainerType
    {
      get { return (Type)GetValue( ContainerTypeProperty ); }
      set { SetValue( ContainerTypeProperty, value ); }
    }

    internal virtual void GeneratorStateChanged( GeneratorStatus status ) {}

    protected override DependencyObject GetContainerForItemOverride()
    {
      ButtonBase result = null;

      if ( ContainerType != null )
        result = Activator.CreateInstance( ContainerType ) as ButtonBase;

      if ( result == null )
        result = new RadioButton();

      if ( result is RadioButton )
      {
        result.SetBinding( System.Windows.Controls.RadioButton.GroupNameProperty, new Binding( "GroupName" )
                                                                                  {
                                                                                    Source = this
                                                                                  } );
      }

      if ( result is ToggleButton )
      {
        var pd = DependencyPropertyDescriptor.FromProperty( ToggleButton.IsCheckedProperty, result.GetType() );
        pd.AddValueChanged( result, ( sender, args )=>OnSelectionChanged( ( (ContentControl)sender ).Content ) );
      }
      else
        result.Click += ( sender, args )=>OnSelectionChanged( ( (ContentControl)sender ).Content );

      return result;
    }

    protected virtual void OnSelectionChanged( object content ) {}
  }
}
